package com.zby.openApi.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zby.OpenApiCommon.model.entity.UserInterfaceInfoEntity;
import com.zby.openApi.common.ErrorCode;
import com.zby.openApi.dao.UserInterfaceInfoDao;
import com.zby.openApi.exception.BusinessException;
import com.zby.openApi.service.UserInterfaceInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("userInterfaceInfoService")
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoDao, UserInterfaceInfoEntity> implements UserInterfaceInfoService {

    @Resource
    private UserInterfaceInfoDao userInterfaceInfoDao;

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfoEntity userInterfaceInfoEntity, boolean add) {
        if (userInterfaceInfoEntity == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 创建时，所有参数必须非空
        if (add) {
            if (userInterfaceInfoEntity.getInterfaceinfoid() <= 0 || userInterfaceInfoEntity.getUserid() <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口或用户不存在");
            }
        }
        if (userInterfaceInfoEntity.getLeftnum() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余次数不能小于 0");
        }
    }

    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        // 判断
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UpdateWrapper<UserInterfaceInfoEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("interfaceinfoid", interfaceInfoId);
        updateWrapper.eq("userid", userId);
        updateWrapper.setSql("totalNum = totalNum + 1");
        UserInterfaceInfoEntity userInterfaceInfoEntity = userInterfaceInfoDao.selectOne(updateWrapper);
        if (userInterfaceInfoEntity != null) {
            return this.update(updateWrapper);
        }
        userInterfaceInfoEntity = new UserInterfaceInfoEntity();
        userInterfaceInfoEntity.setId(userId);
        userInterfaceInfoEntity.setInterfaceinfoid(interfaceInfoId);
        userInterfaceInfoEntity.setTotalnum(1);
        return this.save(userInterfaceInfoEntity);
    }

}
